package experimentseswc;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDB;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;

public class JenaTDBStore implements Store {
	
	private Dataset dataset;
	private static String dir="/home/gabriela/database1";
	
	public JenaTDBStore() {
		File d = new File(dir);
		System.out.println("mkdir: "+d.mkdir());
		dataset = TDBFactory.createDataset(dir) ;
		//TDB.getContext().set(TDB.symUnionDefaultGraph, true);
	}
	
	public void loadIn(String fileName) {
		//String name = fileName.substring(fileName.lastIndexOf('/'), fileName.lastIndexOf('.'));
		//Model m = dataset.getNamedModel("http://datasets/"+name) ;
		Model m = dataset.getDefaultModel(); 
		FileManager.get().readModel(m, fileName);
		//m.read(fileName);
	}
	
	public Iterator<ArrayList<String>> executeSelect(String query, ArrayList<String> vs) { 

		return new SolutionsIter(query, vs);
	}
	
	public long size() {
		long s = dataset.getDefaultModel().size();
		Iterator<String> it = dataset.listNames();
		while (it.hasNext()) {
			Model m = dataset.getNamedModel(it.next());
			s = s + m.size();
		}
		return s;
	}

	public void close() {
		dataset.close();
		File d = new File("dir");
		d.deleteOnExit();
	}
	
	private class SolutionsIter implements Iterator<ArrayList<String>> {

		ResultSet rs;
		ArrayList<String> vars;
		
		public SolutionsIter(String query, ArrayList<String> vs) {
			
			QueryExecution result = QueryExecutionFactory.create(query, dataset);
			vars = vs;
			rs = result.execSelect(); 	
		}

		public boolean hasNext() {
			
			return rs.hasNext();
		}

		public ArrayList<String> next() {
			
			QuerySolution binding = rs.nextSolution();
			ArrayList<String> s = new ArrayList<String>();
			for (String var : vars) {
				String val = binding.get(var).toString();
				s.add(val);
			}
			return s;
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}	
}